import json
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

bandit_event_project_api = Blueprint('bandit_event_project_api', __name__)
bandit_event_project_down_api = Blueprint('bandit_event_project_down_api', __name__)
bandit_event_project_sync_api = Blueprint('bandit_event_project_sync_api', __name__)


@bandit_event_project_api.route('/bandit_event_project', methods=['POST'])
def bandit_event_project():
    params = json.loads(request.data)

    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}

    if _action == 'detail':
        query = BanditEventProject.query.filter_by(project=_project).first()
        basic = json.loads(query.basic)
        tmp = {
            "project": int(query.project),
            'basic': basic,
            'reward': json.loads(query.reward)
        }
        result_data['data']['item'] = tmp

    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']

        if _part == 'basic':
            BanditEventProject.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })
        elif _part == 'user_rank':
            project_data = BanditEventProject.query.filter_by(project=_project).first()
            _reward = json.loads(project_data.reward)
            _reward['user_rank_reward'] = _data
            project_data.reward = json.dumps(_reward)
        elif _part == 'user_goal':
            project_data = BanditEventProject.query.filter_by(project=_project).first()
            _reward = json.loads(project_data.reward)
            _reward['user_goal_reward_list'] = _data
            project_data.reward = json.dumps(_reward)
        elif _part == 'alliance_rank':
            project_data = BanditEventProject.query.filter_by(project=_project).first()
            _reward = json.loads(project_data.reward)
            _reward['al_rank_reward'] = _data
            project_data.reward = json.dumps(_reward)
        elif _part == 'alliance_goal':
            project_data = BanditEventProject.query.filter_by(project=_project).first()
            _reward = json.loads(project_data.reward)
            _reward['al_goal_reward_list'] = _data
            project_data.reward = json.dumps(_reward)
        elif _part == 'score_list':
            project_data = BanditEventProject.query.filter_by(project=_project).first()
            _reward = json.loads(project_data.reward)
            _reward['score_list'] = _data
            project_data.reward = json.dumps(_reward)

        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    
    elif _action == 'calendar_doc_id_list':
        return json.dumps(GetNewOperationEventList('boss_incoming_event', 'title'))
    
    elif _action == 'event_ui_list':
        with open(STATIC_PATH + 'bandit_event_project/event_ui_list.json', encoding='UTF-8') as f:
            data = json.load(f)
            result = []
            for i in data:
                result.append({
                    "value": i['value'],
                    "label": f"{i['value']} - {i['label']}"
                })
            return json.dumps(result)

    elif _action == 'score_type_list':
        with open(STATIC_PATH + 'bandit_event_project/score_type.json', encoding='UTF-8') as f:
            data = json.load(f)
            return json.dumps(data)

    # elif _action == 'difficult_limit_list':
    #     content = loadGame()['game_bandit_attack']
    #     result = []
    #     for k in content.keys():
    #         result.append({
    #             'value': int(k),
    #             'label': f'难度-{k}'
    #             })
    #     return json.dumps(result)

    return jsonify(result_data)


@bandit_event_project_down_api.route('/bandit_event_project_down/<int:is_push>', methods=['GET', 'POST'])
def bandit_event_project_down(is_push):
    bandit_event_project = {}

    query = BanditEventProject.query.order_by('project').all()

    for q in query:
        project = int(q.project)
        basic = json.loads(q.basic)
        reward = json.loads(q.reward)

        _reward = {
            'goal_reward': {
                'al_goal_reward_list': [],
                'user_goal_reward_list': []
            },
            'rank_reward': {
                'user_rank_reward': [],
                'al_rank_reward': []
            }
        }
        for i in reward['user_rank_reward']:
            _reward['rank_reward']['user_rank_reward'].append({
                'from': i['from'],
                'to': i['to'],
                'reward': RewardToTMysqlNew(i['reward'])
            })
        for i in reward['user_goal_reward_list']:
            _reward['goal_reward']['user_goal_reward_list'].append({
                'from': 1,
                'to': i['to'],
                'reward': RewardToTMysqlNew(i['reward'])
            })
        for i in reward['al_rank_reward']:
            _reward['rank_reward']['al_rank_reward'].append({
                'from': i['from'],
                'to': i['to'],
                'reward': RewardToTMysqlNew(i['reward'])
            })
        for i in reward['al_goal_reward_list']:
            _reward['goal_reward']['al_goal_reward_list'].append({
                'from': 1,
                'to': i['to'],
                'reward': RewardToTMysqlNew(i['reward'])
            })
        _score_type_list = []
        with open(STATIC_PATH + 'bandit_event_project/score_type.json', encoding='UTF-8') as f:
            score_type_list = json.load(f)
        for i in reward['score_list']:
            for j in score_type_list:
                if i['value'] == j['value']:
                    _score_type_list.append({
                        'division': i['division'],
                        'points': i['points'],
                        'score_id_map': j['score_id_map'],
                        'score_type': j['score_type'],
                        'to_al': j['to_al']
                    })

        _tag = basic['_tag'] if '_tag' in basic else []
        
        # 20230221 5.1 新增 difficult_limit 字段
        # 10120201 5.1 回滚协议
        # difficult_limit = basic['difficult_limit'] if 'difficult_limit' in basic else 16

        bandit_event_project[str(project)] = {
            '_tag': _tag,
            'calendar_conf': {
                'event_type': 16,
                'event_ui': 1,
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': basic['calendar_doc_id'],
                    'info': basic['calendar_doc_id']
                },
                'reward': RewardToTMysqlNew(basic['calendar_reward']),
                'show_type': 0
            },
            'basic': {
                'event_ui': basic['event_ui']
            },
            'calc_score': {
                'score_type_list': _score_type_list
            },
            'localization': json.loads(q.localization),
            'reward': _reward
        }
    if is_push == 0:
        response = DownLoad('bandit_event_project', bandit_event_project, 0)
    if is_push == 1:
        r1 = DownLoad('bandit_event_project', bandit_event_project, 1)
        if r1:
            return jsonify({"msg": "发布成功", "ret": 1})
        else:
            return False
    return response


@bandit_event_project_sync_api.route('/bandit_event_project_sync', methods=['GET', 'POST'])
def bandit_event_project_sync():
    reward_list = rewardList()

    def RewardShowToDocBonus3(reward_list, reward_item_list={}):
        if len(reward_item_list) == 0:
            reward_item_list = rewardList()
        result_bonus = []
        for x in range(len(reward_list)):
            item_type = reward_list[x]['a'][0]
            item_id = reward_list[x]['a'][1]
            item_num = reward_list[x]['a'][2]
            # print(item_type in reward_item_list)
            if item_type in reward_item_list['name'] and str(item_id) in reward_item_list['name'][item_type]:
                item_name = reward_item_list['name'][item_type][str(item_id)]
                item_price = 0
                for z in reward_item_list['reward'][item_type]:
                    if z['id'] == int(item_id):
                        item_price = z['price']
                        break
            else:
                item_name = 'ERROR'
                item_price = 0
            # tmp = {"id": item_id, "name": str(item_id) + ' - ' + item_name, "num": item_num, "price": item_price, "type": item_type}
            tmp = {"id": item_id, "name": item_name, "num": item_num, "price": item_price, "type": item_type}
            result_bonus.append(tmp)
        return result_bonus
    def get_reward_info(r, index):
        if len(r) < index + 1:
            return []
        result = RewardShowToDocBonus3(r[index], reward_list)
        return result

    data = {}
    with open(STATIC_PATH + '../sync/bandit_event_project_preprocessing.json', encoding='utf8') as f:
        data = json.load(f)
    print('data length:', len(data))
    _currentIndex = 0
    for i in data:
        _currentIndex += 1
        print('handler: ' + str(_currentIndex) + ' / ' + str(len(data)))
        _project = int(i)
        _basic = data[i]['basic']
        _localization = data[i]['localization']
        _remark = str(_project)
        if "1" in _localization:
            if "title" in _localization["1"]:
                _remark = _localization["1"]["title"]

        if 'calendar_conf' in data[i]:
            _basic['calendar_doc_id'] = data[i]['calendar_conf']['localization']['title']
            _basic['calendar_reward'] = RewardShowToDocBonus3(data[i]['calendar_conf']['reward'], reward_list)
        else:
            _basic['calendar_doc_id'] = 1
            _basic['calendar_reward'] = []



        _reward = {
            'al_goal_reward_list': [],
            'user_goal_reward_list': [],
            'user_rank_reward': [],
            'al_rank_reward': []
        }
        for j in data[i]['reward']['goal_reward']['al_goal_reward_list']:
            _reward['al_goal_reward_list'].append({
                'to': j['to'],
                'reward': RewardShowToDocBonus3(j['reward'], reward_list)
            })
        for j in data[i]['reward']['goal_reward']['user_goal_reward_list']:
            _reward['user_goal_reward_list'].append({
                'to': j['to'],
                'reward': RewardShowToDocBonus3(j['reward'], reward_list)
            })
        for j in data[i]['reward']['rank_reward']['al_rank_reward']:
            _reward['al_rank_reward'].append({
                'from': j['from'],
                'to': j['to'],
                'reward': RewardShowToDocBonus3(j['reward'], reward_list)
            })
        for j in data[i]['reward']['rank_reward']['user_rank_reward']:
            _reward['user_rank_reward'].append({
                'from': j['from'],
                'to': j['to'],
                'reward': RewardShowToDocBonus3(j['reward'], reward_list)
            })

        _score_list = []
        with open(STATIC_PATH + 'bandit_event_project/score_type.json', encoding='UTF-8') as f:
            score_type_list = json.load(f)
        for j in data[i]['calc_score']['score_type_list']:
            for k in score_type_list:
                if k['score_type'] == j['score_type']:
                    _score_list.append({
                        'value': k['value'],
                        'division': j['division'],
                        'points': j['points']
                    })
        _reward['score_list'] = _score_list



        new_project_data = BanditEventProject(
            project=_project,
            basic=json.dumps(_basic),
            localization=json.dumps(_localization),
            reward=json.dumps(_reward),
            remark=_remark
        )
        db.session.add(new_project_data)
    db.session.commit()
    return jsonify({'msg': 'finished'})
